<template>
  <div class="page">
    <div class="weui-cells weui-cells_form">
      <div class="weui-cell">
        <div class="weui-cell__hd " :class="{'weui-cell_warn':isName}"><label class="weui-label">客户姓名</label></div>
        <div class="weui-cell__bd">
            <input class="weui-input" v-model="form.realname"  type="text" placeholder="请输入客户姓名" @input="getName">
        </div>
        <i class="weui-icon-clear" v-if="nameClear" @click="clearItem('realname')"></i>
      </div>
      <div class="weui-cell" style="padding: 20rpx 30rpx;">
        <div class="weui-cell__hd" :class="{'weui-cell_warn':isPhone}"><label class="weui-label">手机号码</label></div>
        <div class="weui-cell__bd">
            <input class="weui-input" v-model="form.phone" type="text" placeholder="请输入手机号码" @input="phoneVal">
        </div>
         <i class="weui-icon-clear" v-if="phoneClear" @click="phoneClearItem()" ></i>
      </div>
      <div class="weui-cell weui-cell_select weui-cell_select-after" style="padding: 20rpx 30rpx;" @click="showSex">
        <div class="weui-cell__hd">
          <label for="" class="weui-label">客户性别</label>
        </div>

        <div class="weui-cell__bd" style="text-align: right;margin-right: 20rpx;">
          {{sex}}
<!--          <select class="weui-select" name="select2">-->
<!--              <option v-for="item in options" value="item.value" :key="item.value">{{item.label}}</option>-->
<!--          </select>-->

        </div>
        <mp-actionsheet ref="actionsheet" :itemList="options" @confirm="confirm"></mp-actionsheet>
      </div>
      <div class="weui-cell weui-cell_select weui-cell_select-after"  style="padding: 20rpx 30rpx;">
        <div class="weui-cell__hd">
          <label for="" class="weui-label">客户生日</label>
        </div>
<!--        {{form.birthday}}-->

        <div class="weui-cell__bd">
          <picker mode="multiSelector" :value="dateTime1" @change="changeDateTime1"  :range="dateTimeArray1">
            <div class="tui-picker-detail" style="text-align: right;margin-right: 20rpx;">

              {{dateTimeArray1[0][dateTime1[0]]}}-{{dateTimeArray1[1][dateTime1[1]]}}-{{dateTimeArray1[2][dateTime1[2]]}}

            </div>
          </picker>
        </div>

      </div>
      <div class="weui-cell weui-cell_select weui-cell_select-after" @click="getCIty" style="padding: 20rpx 30rpx;">
        <div class="weui-cell__hd">
          <label for="" class="weui-label">所在城市</label>
        </div>

        <div class="weui-cell__bd">

            <div class="tui-picker-detail" style="text-align: right;margin-right: 20rpx;">

              {{form.city}}

            </div>

        </div>
<!--        <picker @change="changeMultiPicker3" @columnchange="handlechange" mode = "multiSelector" v-model="multiIndex3" :range="multiArray3">-->
<!--          <div>-->
<!--            <input type="text" v-model="address" placeholder="请选择" disabled>-->
<!--          </div>-->
<!--        </picker>-->

      </div>
      <div class="weui-cell">
        <div class="weui-cell__hd"><label class="weui-label">联系地址</label></div>
        <div class="weui-cell__bd">
            <input class="weui-input" v-model="form.address" type="text" style="text-align: right;" @input="addressVal" placeholder="请输入联系地址">
        </div>
        <i class="weui-icon-clear" v-if="addressClear"  @click="addressClearItem()"></i>
      </div>
      <div class="weui-cell">
        <div class="weui-cell__bd">
            <div>备注说明</div>
            <textarea class="weui-textarea" v-model="form.remark" placeholder="请输入文本" rows="3"></textarea>
        </div>
      </div>
      <div class="weui-cell">
<!--        <div class="weui-cell__bd">-->
<!--            <div class="weui-uploader">-->
<!--                 <div class="weui-uploader__hd">-->
<!--                      <p class="weui-uploader__title"><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">客户头像</font></font></p>-->
<!--                     <div class="weui-uploader__info"><font style="vertical-align: inherit;"><font style="vertical-align: inherit;">{{getLen}}/1</font></font></div>-->
<!--                  </div>-->
<!--                <div class="weui-uploader__bd headerUp" >-->
<!--                    <ul class="weui-uploader__files" id="uploaderFiles" >-->
<!--                        <li class="weui-uploader__file weui-uploader__file_status"-->
<!--                            v-for="(item,index) in images"-->
<!--                            :key="index"-->
<!--                            v-if="images.length"-->
<!--                            :style="{backgroundImage:'url('+item+')'}"-->
<!--                            @click="handleImagePreview"-->
<!--                        >-->
<!--                          <div class="weui-uploader__file-content" @click="remove(index)">-->
<!--&lt;!&ndash;                            <van-icon name="close" />&ndash;&gt;-->
<!--                            <i class="close" >-->
<!--                              ×-->
<!--                            </i>-->
<!--                          </div>-->
<!--                        </li>-->
<!--                      &lt;!&ndash; <li class="weui-uploader__file" style="background-image:url(./images/pic_160.png)"></li>-->
<!--                      <li class="weui-uploader__file" style="background-image:url(./images/pic_160.png)"></li>-->
<!--                      <li class="weui-uploader__file weui-uploader__file_status" style="background-image:url(./images/pic_160.png)">-->
<!--                            <div class="weui-uploader__file-content">-->
<!--                                <i class="weui-icon-warn"></i>-->
<!--                            </div>-->
<!--                        </li> &ndash;&gt;-->

<!--                 </ul>-->
<!--                    <div class="weui-uploader__input-box" v-if="getLen==0">-->
<!--                        <input id="uploaderInput" @click="upload" class="weui-uploader__input" type="file" accept="image/*" multiple="">-->
<!--                    </div>-->
<!--                </div>-->
<!--            </div>-->
<!--        </div>-->
    </div>
    </div>
    <div class="weui-btn-area">
      <a class="weui-btn weui-btn_primary" @click="submit" id="showTooltips">确定</a>
    </div>

<!--    <mp-datepicker ref="mpDatePicker" :defaultDate="defaultDate"  @onConfirm="dateCom"></mp-datepicker>-->
<!--    <mp-citypicker ref="mpCityPicker" :pickerValueDefault="pickerValueDefault"  @onConfirm="onConfirm"></mp-citypicker>-->
    <div class="mpvue-picker">
      <div :class="{'pickerMask':showPicker}" @click="maskClick" catchtouchmove="true"></div>
      <div class="mpvue-picker-content " :class="{'mpvue-picker-view-show':showPicker}">
        <div class="mpvue-picker__hd" catchtouchmove="true">
          <div class="mpvue-picker__action" @click="pickerCancel">取消</div>
          <div class="mpvue-picker__action" :style="{color:themeColor}" @click="pickerConfirm">确定</div>
        </div>
        <picker-view indicator-style="height: 40px;" class="mpvue-picker-view" :value="pickerValue" @change="pickerChange">
          <block>
            <picker-view-column>
              <div class="picker-item" v-for="(item,index) in provinceDataList" :key="index">{{item.label}}</div>
            </picker-view-column>
            <picker-view-column>
              <div class="picker-item" v-for="(item,index) in cityDataList" :key="index">{{item.label}}</div>
            </picker-view-column>
            <picker-view-column>
              <div class="picker-item" v-for="(item,index) in areaDataList" :key="index">{{item.label}}</div>
            </picker-view-column>
          </block>
        </picker-view>
      </div>
    </div>
  </div>
</template>

<script>
  import mpActionsheet from 'mpvue-weui/src/actionsheet';
  import mpDatepicker from 'mpvue-weui/src/date-picker';
  import mpCitypicker from 'mpvue-weui/src/city-picker';
  import mpUploader from 'mpvue-weui/src/uploader'
  import {dateTimePicker}  from '../../utils/index';
  import provinceData from '../../utils/province.js';
  import cityData from '../../utils/city.js';
  import areaData from '../../utils/area.js';
export default {
  components:{
    mpActionsheet,
    mpDatepicker,
    mpCitypicker,
    mpUploader
  },
  data () {
    return {
      pickerValueDefault:[0,0,0],
      pickerValue: [0, 0, 0],
      provinceDataList: [],
      cityDataList: [],
      areaDataList: [],
      showPicker: false,
      dateTimeArray1: null,
      dateTime1: null,
      startYear: 1949,
      endYear: 2100,

      date: '1990-01-01 00:00:00',
      isName:false,
      isPhone:false,
      sex:"",
      nameClear:false,
      phoneClear:false,
      addressClear:false,
      form:{
        sex:"",
        birthday:"",
        city:"",
        address:"",
        remark:"",
        img:""
      },
      images:[],
      baseList:[],
      options: [
       '男','女'
      ],
      multiArray3: [[], [], []],
      multiIndex3: [0, 0, 0],
      areaCode: '',
      sheng: '',
      shi: '',
      qu: '',
      address: ''

    }
  },
  computed:{
    getLen(){
      return this.images.length;
    }
  },

  onShow(){
    // this.form={
    //     sex:"",
    //     birthday:"",
    //     city:"",
    //     address:"",
    //     remark:"",
    //     img:""
    //   },
    this.getCurrentTime();
    this.images=[];
    let tempPickerValue = this.handPickValueDefault();
    this.provinceDataList = provinceData;
    this.cityDataList = cityData[this.pickerValueDefault[0]];
    this.areaDataList = areaData[this.pickerValueDefault[0]][this.pickerValueDefault[1]];
    setTimeout(() => {
      this.pickerValue = tempPickerValue;
    });
    wx.setNavigationBarTitle({
          title: "添加顾客"
      })
    this.userInfo =wx.getStorageSync('userInfo')&&JSON.parse(wx.getStorageSync('userInfo'))
    if(this.userInfo) {
      this.phone=this.userInfo.mobileNo;
      this.userId=this.userInfo.baseUserId;
      //this. getList(0)



    }else{
      wx.showToast({
        title:'请先登录',
        icon: 'none',
        duration: 2000
      })
    }
    // this.$refs.uploader.show()
  },
  methods: {
    // 日期
    //修改时间时方法
    changeDateTime1(e) {
      this.dateTime1 = e.mp.detail.value;
      let yyyy = this.dateTimeArray1[0][this.dateTime1[0]];
      let mm = this.dateTimeArray1[1][this.dateTime1[1]];
      let dd = this.dateTimeArray1[2][this.dateTime1[2]];
      let hh = this.dateTimeArray1[3][this.dateTime1[3]];
      let min = this.dateTimeArray1[4][this.dateTime1[4]];
      let dateStr =`${yyyy}-${mm}-${dd} ${hh}:${min}`
      let timestamp = new Date(dateStr).getTime();
      this.form.crimeTime =  timestamp;
    },


    //获取当前时间
    getCurrentTime(){
      // 获取完整的年月日 时分秒，以及默认显示的数组
      var obj = dateTimePicker(this.startYear, this.endYear, this.date);
      // 精确到分的处理，将数组的秒去掉
      var lastArray = obj.dateTimeArray.pop();
      this.dateTimeArray1 = obj.dateTimeArray;
      this.dateTime1 = obj.dateTime;

      let yyyy = this.dateTimeArray1[0][this.dateTime1[0]];
      let mm = this.dateTimeArray1[1][this.dateTime1[1]];
      let dd = this.dateTimeArray1[2][this.dateTime1[2]];
      let hh = this.dateTimeArray1[3][this.dateTime1[3]];
      let min = this.dateTimeArray1[4][this.dateTime1[4]];
      let dateStr =`${yyyy}-${mm}-${dd} ${hh}:${min}`
      let timestamp = new Date(dateStr).getTime();
      this.form.crimeTime =  timestamp;
    },
    // 城市
    showCity() {
      setTimeout(() => {
        this.showPicker = true;
      }, 0);
    },
    maskClick() {
      this.pickerCancel();
    },
    pickerCancel() {
      this.showPicker = false;
      this.onCancel()
      //this._$emit('onCancel');
    },
    pickerConfirm(e) {
      this.showPicker = false;
      // this.onConfirm()
      this._$emit('onConfirm');
    },
    showPickerView() {
      this.showPicker = true;
    },
    handPickValueDefault() {
      let tempPickerValue = this.pickerValueDefault;
      if (this.pickerValueDefault !== [0, 0, 0]) {
        if (this.pickerValueDefault[0] > provinceData.length - 1) {
          tempPickerValue[0] = provinceData.length - 1;
        }
        if (this.pickerValueDefault[1] > cityData[tempPickerValue[0]].length - 1) {
          tempPickerValue[1] = cityData[tempPickerValue[0]].length - 1;
        }
        if (this.pickerValueDefault[2] > areaData[tempPickerValue[0]][tempPickerValue[1]].length - 1) {
          tempPickerValue[2] = areaData[tempPickerValue[0]][tempPickerValue[1]].length - 1;
        }
      }
      return tempPickerValue;
    },
    pickerChange(e) {
      let changePickerValue = e.mp.detail.value;
      if (this.pickerValue[0] !== changePickerValue[0]) {
        // 第一级发生滚动
        this.cityDataList = cityData[changePickerValue[0]];
        this.areaDataList = areaData[changePickerValue[0]][0];
        changePickerValue[1] = 0;
        changePickerValue[2] = 0;
      } else if (this.pickerValue[1] !== changePickerValue[1]) {
        // 第二级滚动
        this.areaDataList =
          areaData[changePickerValue[0]][changePickerValue[1]];
        changePickerValue[2] = 0;
      }
      this.pickerValue = changePickerValue;
      this._$emit('onChange');
    },
    _$emit(emitName) {
      let pickObj = {
        label: this._getLabel(),
        value: this.pickerValue,
        cityCode: this._getCityCode()
      };
      this.onConfirm(pickObj)
      //this.$emit(emitName, pickObj);
    },
    _getLabel() {
      let pcikerLabel =
        this.provinceDataList[this.pickerValue[0]].label +
        '-' +
        this.cityDataList[this.pickerValue[1]].label +
        '-' +
        this.areaDataList[this.pickerValue[2]].label;
      return pcikerLabel;
    },
    _getCityCode() {
      return this.areaDataList[this.pickerValue[2]].value;
    },
    addressClearItem(){
      this.form.address=""
      this.$set(this.form,this.form.address,'')
      this.$forceUpdate();
    },
    clearItem(item){
      console.log( this.form[item])
      this.form.realname=""
      this.$set(this.form,this.form.realname,'')
      this.$forceUpdate();
    },
    phoneClearItem(){
      this.form.phone=""
      this.$set(this.form,this.form.phone,'')
      this.$forceUpdate();
    },
    addressVal(){
      // addressClear
      if(this.form.address){
        this.addressClear=true;
      }else{
        this.addressClear=false;
      }
    },
    phoneVal(){
      if(this.form.phone){
        this.phoneClear=true;
      }else{
        this.phoneClear=false;
      }
    },
    getName(){
     if(this.form.realname){
       this.nameClear=true;
     }else{
       this.nameClear=false;
     }
    },
    remove(inex){
      this.images.splice(inex,1)
    },
    urlTobase64(url){
       var that = this;
        wx.request({
          url:url,
          responseType: 'arraybuffer', //最关键的参数，设置返回的数据格式为arraybuffer
          success:res=>{
    	      //把arraybuffer转成base64
                let base64 = wx.arrayBufferToBase64(res.data);

                //不加上这串字符，在页面无法显示的哦
                base64　= 'data:image/jpeg;base64,' + base64　

                //打印出base64字符串，可复制到网页校验一下是否是你选择的原图片呢
                that.form.img=base64;
              //  that.baseList.push(base64)
                // console.log(base64)　
              }
        })
     },

    handleImagePreview(e){
      const idx = e.target.dataset.idx;
      const imagesList = this.images;

      wx.previewImage({
        current: imagesList[idx],  //当前预览的图片
        urls: imagesList,  //所有要预览的图片
      })
    },
     upload(e) {
            var that = this,
              i=0,
              imgFilePaths="",
              upLength=0;
            wx.chooseImage({
                count: 1 , // 默认9
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function(res) {
                  console.log(res.tempFilePaths)
                     that.images.push(res.tempFilePaths[0])
                     // that. urlTobase64(res.tempFilePaths[0])
                  imgFilePaths = res.tempFilePaths;
                  upLength = imgFilePaths.length;
                  // if(len.length > max){
                  //   that.$mptoast('图片最多只能选择' + max);
                  //   return false;
                  // }
                  /**
                   * 上传完成后把文件上传到服务器
                   */
                  wx.showLoading({
                    title: '上传中...',
                  })
                  that.upLoad(imgFilePaths,i,upLength);
                }
            })
        },
    upLoad(imgPath,i,upLength){
      let that = this;
      let token=wx.getStorageSync('Authorization')
      console.log(imgPath[i])
      //上传文件
      wx.uploadFile({
        url: `https://xcx.saas.apis.huidianzhang.com:8080/hdz-apprest/v1.0/appletLogin/customerImage`,
        filePath: imgPath[i],
        name: 'file',
        header: {
          "Content-Type": "multipart/form-data",

        },

        success: function (res) {
          console.log(res.data)
          wx.showToast({
            title: '上传成功!',
            icon: 'success',
            duration: 2000,

          })
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          // that.files = that.files.concat(imgPath[i]);        //合并图片显示数组
          // let imgData = JSON.parse(res.data);
          // that.upImg.push(imgData.data);

        },
        fail: function (res) {
          console.log(res);
          wx.hideLoading();
          wx.showModal({
            title: '错误提示',
            content: '上传图片失败',
            showCancel: false,
            success: function (res) { }
          })
        },
        // complete: function(){
        //   i++;
        //   if(i == upLength){
        //     wx.hideLoading();    //上传结束，隐藏loading
        //   }else{
        //     that.upLoad(imgPath,i,upLength);
        //   }
        // }
      });
    },
    submit(){
     this.form.birthday=`${this.dateTimeArray1[0][this.dateTime1[0]]}-${this.dateTimeArray1[1][this.dateTime1[1]]}-${this.dateTimeArray1[2][this.dateTime1[2]]}`;
      this.form.userId=this.userId;
      this.form.img=this.baseList.join(',')
      if(!this.form.realname){
        this.isName=true;
        wx.showToast({
          title: '请输入客户名',
          icon: 'none',
          duration: 2000
        })
      }else
      if(!(/^1[3456789]\d{9}$/.test(this.form.phone))){
        this.isPhone=true;
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
          duration: 2000
        })
      }else{
         this.isName=false;
          this.isPhone=false;
        this.$http.request({
                  method:"post",
                  url:"/v1.0/appletLogin/addCustomers",
                  body:this.form
        }).then((data)=>{
          if(data.code==0){
            this.form={
                sex:"",
                birthday:"",
                city:"",
                address:"",
                remark:"",
                img:""
              },
            wx.showToast({
              title: '添加成功',
              icon: 'success',
              duration: 2000
            })
          }else{
            wx.showToast({
              title: `${data.message}`,
              icon: 'none',
              duration: 2000
            })
          }
        })
      }

    },
    getCIty(){
      this.showCity();
    },
    dateBox(){
      console.log('生日')
      this.$refs.mpDatePicker.show()
    },
    showSex(){
      this.$refs.actionsheet.show()
    },
    dateChange (e) {
      console.log('picker发送选择改变，携带值为', e.mp.detail.value)
    },
    confirm(val){
      console.log(val)
      this.sex=val.tapLabel
      this.form.sex=val.tapIndex
    },
    upLoadSuccess(val){
       console.log(val)
    },
    upLoadFail(){
      wx.showToast({
        title: '上传失败',
        icon: 'none',
        duration: 2000
      })
    },
    uploadDelete(){
      wx.showToast({
        title: '已删除',
        icon: 'none',
        duration: 2000
      })
    },
    onConfirm(val){
      this.form.city=val.label;
    },
    dateCom(val){
      console.log(val)
       val.label=val.label.replace(/年/g,'').replace(/月/g,'').replace(/日/g,'')
      this.form.birthday=val.label;
    },
  },

  created () {
    // let app = getApp()
  }
}
</script>
<style>
  .headerUp .weui-uploader__file_status:before{
     background: transparent;
  }
</style>
<style scoped>
   .close{
     width: 18px;
     height: 18px;
     line-height: 33rpx;
     text-align: center;
     position: absolute;top: -100rpx;right: -91rpx;color: #fff;font-size: 18px; background-color: #969799; border-radius: 100%;
   }
  .pickerMask {
    position: fixed;
    z-index: 1000;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
  }
  .mpvue-picker-content {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    transition: all 0.3s ease;
    transform: translateY(100%);
    z-index: 3000;
  }
  .mpvue-picker-view-show {
    transform: translateY(0);
  }
  .mpvue-picker__hd {
    display: flex;
    padding: 9px 15px;
    background-color: #fff;
    position: relative;
    text-align: center;
    font-size: 17px;
  }
  .mpvue-picker__hd:after {
    content: " ";
    position: absolute;
    left: 0;
    bottom: 0;
    right: 0;
    height: 1px;
    border-bottom: 1px solid #e5e5e5;
    color: #e5e5e5;
    transform-origin: 0 100%;
    transform: scaleY(0.5);
  }
  .mpvue-picker__action {
    display: block;
    flex: 1;
    color: #1aad19;
  }
  .mpvue-picker__action:first-child {
    text-align: left;
    color: #888;
  }
  .mpvue-picker__action:last-child {
    text-align: right;
  }
  .picker-item {
    text-align: center;
    line-height: 40px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .mpvue-picker-view {
    position: relative;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 238px;
    background-color: rgba(255, 255, 255, 1);
  }
/* .weui-uploader__bd .weui-uploader__file-content{
  top: 26rpx;
  right: -82rpx;


 } */
</style>
